package com.wzd.imservice.service.impl;

import com.mongodb.client.result.DeleteResult;
import com.wzd.baseservice.exceptionHandler.BaseException;
import com.wzd.commonutils.R;
import com.wzd.imservice.entity.GroupList;
import com.wzd.imservice.entity.GroupUser;
import com.wzd.imservice.entity.Mine;
import com.wzd.imservice.entity.vo.ChatVo;
import com.wzd.imservice.enums.ChatTypeEnum;
import com.wzd.imservice.service.GroupService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ProjectName: e_learning
 * @Package: com.wzd.imservice.service.impl
 * @ClassName: GroupServiceimpl
 * @Author: lofxve
 * @Description:
 * @Date: 2021/4/16 17:03
 * @Version: 1.0
 */
@Service
public class GroupServiceimpl implements GroupService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public R saveGroup(GroupList groupList) {

        groupList.setType(ChatTypeEnum.getNameByKey(1));
        GroupList save = mongoTemplate.save(groupList);
        GroupUser groupUser = GroupUser.builder()
                .gid(save.getId())
                .userId(groupList.getMaster())
                .build();
        mongoTemplate.save(groupUser);
        if (save.getId() != null) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @Override
    public GroupList getGroupById(String id) {
        return mongoTemplate.findById(id, GroupList.class);
    }

    @Override
    public R addUserToGroup(Mine mineById, GroupList groupById) {
        Query query = new Query(Criteria.where("gid").is(groupById.getId()).and("userId").is(mineById.getId()));
        List<GroupUser> groupUsers = mongoTemplate.find(query, GroupUser.class);
        if (CollectionUtils.isEmpty(groupUsers)) {
            // 查询
            Query id = new Query(Criteria.where("_id").is(groupById.getId()));
            // 更新数据
            Update update = new Update();
            List<Mine> userList = groupById.getUserList();
            userList.add(mineById);
            update.set("userList", userList);
            // 修改
            mongoTemplate.updateFirst(id, update, GroupList.class);
            GroupUser groupUser = GroupUser.builder()
                    .gid(groupById.getId())
                    .userId(mineById.getId())
                    .build();
            mongoTemplate.save(groupUser);
            return R.ok();

        } else {
            return R.ok().message("用户存在，无需重复添加");
        }
    }

    @Override
    public R deleteUserFromGroup(Mine mineById, GroupList groupById) {
        Query query = new Query(Criteria.where("gid").is(groupById.getId()).and("userId").is(mineById.getId()));
        List<GroupUser> groupUsers = mongoTemplate.find(query, GroupUser.class);
        if (CollectionUtils.isEmpty(groupUsers)) {
            throw new BaseException(20001, "用户不在此班级");
        }
        // 删除
        mongoTemplate.remove(query, GroupUser.class);
        // 查询
        Query id = new Query(Criteria.where("_id").is(groupById.getId()));
        // 更新数据
        Update update = new Update();
        List<Mine> userList = groupById.getUserList();
        userList.remove(mineById);
        update.set("userList", userList);
        // 修改
        mongoTemplate.updateFirst(id, update, GroupList.class);
        return R.ok();
    }

    @Override
    public R getGroupsByUserId(Mine mineById) {
        // 获取用户分组列表
        Query query = new Query(Criteria.where("userId").is(mineById.getId()));
        List<GroupUser> groupUsers = mongoTemplate.find(query, GroupUser.class);

        ArrayList<ChatVo> chatVoArrayList = new ArrayList<>();
        for (GroupUser groupUser : groupUsers) {
            // 查询班级
            Query queryGroup = new Query(Criteria.where("_id").is(groupUser.getGid()));
            List<GroupList> groupLists = mongoTemplate.find(queryGroup, GroupList.class);
            GroupList groupList = groupLists.get(0);
            if (groupList != null) {
                // 班级内的用户
                List<Mine> userList = groupList.getUserList();
                if (!CollectionUtils.isEmpty(userList)) {
                    for (Mine mine : userList) {
                        ChatVo chatMineVo = new ChatVo();
                        BeanUtils.copyProperties(mine, chatMineVo);
                        chatVoArrayList.add(chatMineVo);
                    }
                }
                ChatVo chatVo = new ChatVo();
                BeanUtils.copyProperties(groupList, chatVo);
                chatVoArrayList.add(chatVo);
            }
        }
        // 删除用户自己
        for (int i = chatVoArrayList.size() - 1; i >= 0; i--) {
            ChatVo chatVo = chatVoArrayList.get(i);
            if (mineById.getId().equals(chatVo.getId())) {
                chatVoArrayList.remove(i);
            }
            chatVo.setMessageSize(0);
        }
        // 重写equals和haseCode 去重
        List<ChatVo> collect = chatVoArrayList.stream().distinct().collect(Collectors.toList());
        return R.ok().data("chatVoArrayList", collect);
    }

    @Override
    public boolean deleteGroup(String id) {
        Query query = new Query(Criteria.where(id).is(id));
        GroupList one = mongoTemplate.findOne(query, GroupList.class);
        List<Mine> userList = one.getUserList();
        // 将用户从班级中删除
        for (Mine mine : userList) {
            this.deleteUserFromGroup(mine,one);
        }
        // 删除班级
        DeleteResult remove = mongoTemplate.remove(query, GroupList.class);
        long deletedCount = remove.getDeletedCount();
        if (deletedCount > 0) {
            return true;
        } else {
            return false;
        }
    }
}
